<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合格证编号" prop="qualificationNo" label-width="100px">
        <el-input
          v-model="queryParams.qualificationNo"
          placeholder="请输入合格证编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户完善信息" prop="userPerfectId" label-width="125px">
        <el-input
          v-model="queryParams.userPerfectId"
          placeholder="请输入用户完善信息"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主体名称" prop="subjectName">
        <el-input
          v-model="queryParams.subjectName"
          placeholder="请输入主体名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产地信息" prop="productArea">
        <el-input
          v-model="queryParams.productArea"
          placeholder="请输入产地信息"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省" prop="province">
        <el-select
          v-model="queryParams.province"
          placeholder="请选择省"
          clearable
          filterable
          @change="handleProvinceChange"
        >
          <el-option
            v-for="item in provinceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="city">
        <el-select
          v-model="queryParams.city"
          placeholder="请选择市"
          clearable
          filterable
          @change="handleCityChange"
        >
          <el-option
            v-for="item in cityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="区/县" prop="area">
        <el-select
          v-model="queryParams.area"
          placeholder="请选择区/县"
          clearable
          filterable
          @change="handleAreaChange"
        >
          <el-option
            v-for="item in areaOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="乡镇/街道" prop="country" label-width="120px">
        <el-select
          v-model="queryParams.country"
          placeholder="请选择乡镇/街道"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option
            v-for="item in countryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否打印合格证抬头" prop="qualificationTitleFlag" label-width="200px">
        <el-select
          v-model="queryParams.qualificationTitleFlag"
          placeholder="请选择是否打印合格证抬头"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['nongjt:qualification:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['nongjt:qualification:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['nongjt:qualification:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['nongjt:qualification:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="qualificationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="合格证编号" align="center" prop="qualificationNo" width="120"/>
      <el-table-column label="用户账号" align="center" prop="userId" />
      <el-table-column label="用户完善信息" align="center" prop="userPerfectId" width="130"/>
      <el-table-column label="主体名称" align="center" prop="subjectName" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品数量" align="center" prop="productCount" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="产地信息" align="center" prop="productArea" />
      <el-table-column label="省" align="center" prop="province" />
      <el-table-column label="市" align="center" prop="city" />
      <el-table-column label="区/县" align="center" prop="area" />
      <el-table-column label="乡镇/街道" align="center" prop="country" />
      <el-table-column label="开具日期" align="center" prop="issueDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检测报告" align="center" prop="detectReport">
        <template #default="scope">
          <image-preview :src="scope.row.detectReport" :width="80" :height="80" v-if="scope.row.detectReport" />
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="检测报告类型" align="center" prop="detectReportType" />
      <el-table-column label="是否打印合格证抬头" align="center" prop="qualificationTitleFlag" />
      <el-table-column label="签名图片" align="center" prop="signUrl">
        <template #default="scope">
          <image-preview :src="scope.row.signUrl" :width="80" :height="80" v-if="scope.row.signUrl" />
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="打印次数" align="center" prop="printCount" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nongjt:qualification:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nongjt:qualification:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合格证信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="qualificationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合格证编号" prop="qualificationNo" label-width="100">
          <el-input v-model="form.qualificationNo" placeholder="请输入合格证编号" />
        </el-form-item>
        <el-form-item label="用户账号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="用户完善信息" prop="userPerfectId" label-width="120">
          <el-input v-model="form.userPerfectId" placeholder="请输入用户完善信息" />
        </el-form-item>
        <el-form-item label="主体名称" prop="subjectName">
          <el-input v-model="form.subjectName" placeholder="请输入主体名称" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品数量" prop="productCount">
          <el-input v-model="form.productCount" placeholder="请输入产品数量" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="产地信息" prop="productArea">
          <el-input v-model="form.productArea" placeholder="请输入产地信息" />
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-select 
            v-model="form.province" 
            placeholder="请选择省" 
            filterable
            @change="handleFormProvinceChange"
          >
            <el-option
              v-for="item in provinceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select 
            v-model="form.city" 
            placeholder="请选择市" 
            filterable
            @change="handleFormCityChange"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="area">
          <el-select 
            v-model="form.area" 
            placeholder="请选择区/县" 
            filterable
            @change="handleFormAreaChange"
          >
            <el-option
              v-for="item in areaOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="乡镇/街道" prop="country" label-width="100">
          <el-select 
            v-model="form.country" 
            placeholder="请选择乡镇/街道" 
            filterable
          >
            <el-option
              v-for="item in countryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开具日期" prop="issueDate">
          <el-date-picker clearable
            v-model="form.issueDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开具日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="检测报告" prop="detectReport">
          <image-upload v-model="form.detectReport" :limit="3" :file-size="5" />
        </el-form-item>
        <el-form-item label="签名图片" prop="signUrl">
          <image-upload v-model="form.signUrl" :limit="1" :file-size="5" />
        </el-form-item>

        <el-form-item label="是否打印合格证抬头" prop="qualificationTitleFlag" label-width="180">
          <el-switch 
            v-model="form.qualificationTitleFlag" 
            :active-value="'1'" 
            :inactive-value="'0'"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>

        <el-form-item label="打印次数" prop="printCount">
          <el-input-number v-model="form.printCount" :min="0" placeholder="请输入打印次数" />
        </el-form-item>
        <el-form-item label="删除标记" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标记" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Qualification">
import { listQualification, getQualification, delQualification, addQualification, updateQualification } from "@/api/nongjt/qualification"
import { listByParentCode } from "@/api/nongjt/area"
import { onMounted } from 'vue'
import ImagePreview from "@/components/ImagePreview"
import ImageUpload from "@/components/ImageUpload"

const { proxy } = getCurrentInstance()

const qualificationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 地区相关数据
const provinceOptions = ref([])
const cityOptions = ref([])
const areaOptions = ref([])
const countryOptions = ref([])

// 获取省份数据
function getProvinceOptions() {
  console.log('开始获取省份数据...')
  return listByParentCode({ parentCode: null }).then(response => {
    console.log('省份数据响应:', response)
    console.log('响应数据类型:', typeof response)
    
    // 由于响应拦截器已经处理过了，直接使用数据
    if (Array.isArray(response)) {
      provinceOptions.value = response.map(item => ({
        value: item.name || item.label || item.title,  // 使用name作为value
        label: item.name || item.label || item.title,
        code: item.code  // 保留code用于获取下级数据
      }))
      console.log('省份选项:', provinceOptions.value)
    } else if (response && typeof response === 'object') {
      // 如果是对象，尝试查找数据数组
      let data = response.data || response.rows || response.list || response.result || []
      if (Array.isArray(data)) {
        provinceOptions.value = data.map(item => ({
          value: item.name || item.label || item.title,  // 使用name作为value
          label: item.name || item.label || item.title,
          code: item.code  // 保留code用于获取下级数据
        }))
        console.log('省份选项:', provinceOptions.value)
      }
    }
  }).catch(error => {
    console.error('获取省份数据异常:', error)
  })
}

// 根据省份获取城市数据
function getCityOptions(provinceCode) {
  console.log('开始获取城市数据，省份code:', provinceCode)
  if (!provinceCode) {
    cityOptions.value = []
    areaOptions.value = []
    countryOptions.value = []
    return Promise.resolve()
  }
  
  return listByParentCode({ parentCode: provinceCode }).then(response => {
    console.log('城市数据响应:', response)
    
    // 直接使用数据
    if (Array.isArray(response)) {
      cityOptions.value = response.map(item => ({
        value: item.name || item.label || item.title,  // 使用name作为value
        label: item.name || item.label || item.title,
        code: item.code  // 保留code用于获取下级数据
      }))
      console.log('城市选项:', cityOptions.value)
    } else if (response && typeof response === 'object') {
      // 如果是对象，尝试查找数据数组
      let data = response.data || response.rows || response.list || response.result || []
      if (Array.isArray(data)) {
        cityOptions.value = data.map(item => ({
          value: item.name || item.label || item.title,  // 使用name作为value
          label: item.name || item.label || item.title,
          code: item.code  // 保留code用于获取下级数据
        }))
        console.log('城市选项:', cityOptions.value)
      }
    }
    
    // 清空后续地区选项
    areaOptions.value = []
    countryOptions.value = []
  }).catch(error => {
    console.error('获取城市数据异常:', error)
    cityOptions.value = []
  })
}

// 根据城市获取区县数据
function getAreaOptions(cityCode) {
  console.log('开始获取区县数据，城市code:', cityCode)
  if (!cityCode) {
    areaOptions.value = []
    countryOptions.value = []
    return Promise.resolve()
  }
  
  return listByParentCode({ parentCode: cityCode }).then(response => {
    console.log('区县数据响应:', response)
    
    // 直接使用数据
    if (Array.isArray(response)) {
      areaOptions.value = response.map(item => ({
        value: item.name || item.label || item.title,  // 使用name作为value
        label: item.name || item.label || item.title,
        code: item.code  // 保留code用于获取下级数据
      }))
      console.log('区县选项:', areaOptions.value)
    } else if (response && typeof response === 'object') {
      // 如果是对象，尝试查找数据数组
      let data = response.data || response.rows || response.list || response.result || []
      if (Array.isArray(data)) {
        areaOptions.value = data.map(item => ({
          value: item.name || item.label || item.title,  // 使用name作为value
          label: item.name || item.label || item.title,
          code: item.code  // 保留code用于获取下级数据
        }))
        console.log('区县选项:', areaOptions.value)
      }
    }
    
    // 清空后续地区选项
    countryOptions.value = []
  }).catch(error => {
    console.error('获取区县数据异常:', error)
    areaOptions.value = []
  })
}

// 根据区县获取乡镇/街道数据
function getCountryOptions(areaCode) {
  console.log('开始获取乡镇/街道数据，区县code:', areaCode)
  if (!areaCode) {
    countryOptions.value = []
    return Promise.resolve()
  }
  
  return listByParentCode({ parentCode: areaCode }).then(response => {
    console.log('乡镇/街道数据响应:', response)
    
    // 直接使用数据
    if (Array.isArray(response)) {
      countryOptions.value = response.map(item => ({
        value: item.name || item.label || item.title,  // 使用name作为value
        label: item.name || item.label || item.title,
        code: item.code  // 保留code用于获取下级数据
      }))
      console.log('乡镇/街道选项:', countryOptions.value)
    } else if (response && typeof response === 'object') {
      // 如果是对象，尝试查找数据数组
      let data = response.data || response.rows || response.list || response.result || []
      if (Array.isArray(data)) {
        countryOptions.value = data.map(item => ({
          value: item.name || item.label || item.title,  // 使用name作为value
          label: item.name || item.label || item.title,
          code: item.code  // 保留code用于获取下级数据
        }))
        console.log('乡镇/街道选项:', countryOptions.value)
      }
    }
  }).catch(error => {
    console.error('获取乡镇/街道数据异常:', error)
    countryOptions.value = []
  })
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    qualificationNo: null,
    userId: null,
    userPerfectId: null,
    subjectName: null,
    productName: null,
    productArea: null,
    province: null,
    city: null,
    area: null,
    country: null,
    qualificationTitleFlag: null,
  },
  rules: {
    qualificationNo: [
      { required: true, message: "合格证编号不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    userPerfectId: [
      { required: true, message: "用户完善信息不能为空", trigger: "blur" }
    ],
    subjectName: [
      { required: true, message: "主体名称不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    productCount: [
      { required: true, message: "产品数量不能为空", trigger: "blur" }
    ],
    unit: [
      { required: true, message: "单位不能为空", trigger: "blur" }
    ],
    issueDate: [
      { required: true, message: "开具日期不能为空", trigger: "change" }
    ],
    province: [
      { required: true, message: "省不能为空", trigger: "change" }
    ],
    city: [
      { required: true, message: "市不能为空", trigger: "change" }
    ],
    area: [
      { required: true, message: "区/县不能为空", trigger: "change" }
    ],
    country: [
      { required: true, message: "乡镇/街道不能为空", trigger: "change" }
    ],
    detectReportType: [
      { required: true, message: "检测报告类型不能为空", trigger: "change" }
    ],
    qualificationTitleFlag: [
      { required: true, message: "是否打印合格证抬头不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询合格证信息列表 */
function getList() {
  console.log('开始获取合格证列表...')
  loading.value = true
  listQualification(queryParams.value).then(response => {
    console.log('合格证列表响应:', response)
    qualificationList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error => {
    console.error('获取合格证信息列表失败:', error)
    loading.value = false
  })
}

// 页面加载时获取省份数据
onMounted(() => {
  console.log('组件挂载完成，开始获取省份数据...')
  // 添加一个简单的测试请求
  listByParentCode({ parentCode: null }).then(response => {
    console.log('测试请求结果:', response)
    console.log('测试请求结果类型:', typeof response)
    console.log('是否为数组:', Array.isArray(response))
    if (Array.isArray(response)) {
      console.log('数组长度:', response.length)
      if (response.length > 0) {
        console.log('第一个元素:', response[0])
      }
    }
  }).catch(error => {
    console.error('测试请求失败:', error)
  })
  
  getProvinceOptions()
})

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    qualificationNo: null,
    userId: null,
    userPerfectId: null,
    subjectName: null,
    productName: null,
    productCount: null,
    unit: null,
    productArea: null,
    province: null,
    city: null,
    area: null,
    country: null,
    issueDate: null,
    detectReport: null,
    detectReportType: null,
    qualificationTitleFlag: '0', // 默认值设为'0'
    signUrl: null,
    printCount: 0,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("qualificationRef")
  // 重置地区选项
  cityOptions.value = []
  areaOptions.value = []
  countryOptions.value = []
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// 省份选择变更事件
function handleProvinceChange(provinceName) {
  queryParams.value.city = null
  queryParams.value.area = null
  queryParams.value.country = null
  // 根据省份名称查找对应的code
  const province = provinceOptions.value.find(item => item.label === provinceName)
  if (province) {
    getCityOptions(province.code)  // 使用code而不是value
  } else {
    cityOptions.value = []
    areaOptions.value = []
    countryOptions.value = []
  }
  handleQuery()
}

// 城市选择变更事件
function handleCityChange(cityName) {
  queryParams.value.area = null
  queryParams.value.country = null
  // 根据城市名称查找对应的code
  const city = cityOptions.value.find(item => item.label === cityName)
  if (city) {
    getAreaOptions(city.code)  // 使用code而不是value
  } else {
    areaOptions.value = []
    countryOptions.value = []
  }
  handleQuery()
}

// 区县选择变更事件
function handleAreaChange(areaName) {
  queryParams.value.country = null
  // 根据区县名称查找对应的code
  const area = areaOptions.value.find(item => item.label === areaName)
  if (area) {
    getCountryOptions(area.code)  // 使用code而不是value
  } else {
    countryOptions.value = []
  }
  handleQuery()
}

// 表单中省份选择变更事件
function handleFormProvinceChange(provinceName) {
  form.value.city = null
  form.value.area = null
  form.value.country = null
  // 根据省份名称查找对应的code
  const province = provinceOptions.value.find(item => item.label === provinceName)
  if (province) {
    getCityOptions(province.code)  // 使用code而不是value
  } else {
    cityOptions.value = []
    areaOptions.value = []
    countryOptions.value = []
  }
}

// 表单中城市选择变更事件
function handleFormCityChange(cityName) {
  form.value.area = null
  form.value.country = null
  // 根据城市名称查找对应的code
  const city = cityOptions.value.find(item => item.label === cityName)
  if (city) {
    getAreaOptions(city.code)  // 使用code而不是value
  } else {
    areaOptions.value = []
    countryOptions.value = []
  }
}

// 表单中区县选择变更事件
function handleFormAreaChange(areaName) {
  form.value.country = null
  // 根据区县名称查找对应的code
  const area = areaOptions.value.find(item => item.label === areaName)
  if (area) {
    getCountryOptions(area.code)  // 使用code而不是value
  } else {
    countryOptions.value = []
  }
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 重置地区选项
  cityOptions.value = []
  areaOptions.value = []
  countryOptions.value = []
  open.value = true
  title.value = "添加合格证信息"
  // 获取省份数据
  getProvinceOptions()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getQualification(_id).then(response => {
    form.value = response.data
    // 处理开关组件的值
    if (form.value.qualificationTitleFlag !== '1') {
      form.value.qualificationTitleFlag = '0'
    }
    open.value = true
    title.value = "修改合格证信息"
    
    // 如果有省份数据，加载对应的下级数据
    if (form.value.province) {
      // 先获取省份列表
      getProvinceOptions().then(() => {
        // 根据省份名称查找对应的code
        const province = provinceOptions.value.find(item => item.label === form.value.province)
        if (province) {
          getCityOptions(province.code).then(() => {
            // 根据城市名称查找对应的code
            const city = cityOptions.value.find(item => item.label === form.value.city)
            if (city) {
              getAreaOptions(city.code).then(() => {
                // 根据区县名称查找对应的code
                const area = areaOptions.value.find(item => item.label === form.value.area)
                if (area) {
                  getCountryOptions(area.code)
                }
              })
            }
          })
        }
      })
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["qualificationRef"].validate(valid => {
    if (valid) {
      // 处理表单数据，确保数值类型正确
      const submitForm = { ...form.value }
      if (submitForm.printCount !== null && submitForm.printCount !== undefined) {
        submitForm.printCount = parseInt(submitForm.printCount) || 0
      }
      
      if (submitForm.id != null) {
        updateQualification(submitForm).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addQualification(submitForm).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除合格证信息编号为"' + _ids + '"的数据项？').then(function() {
    return delQualification(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('nongjt/qualification/export', {
    ...queryParams.value
  }, `qualification_${new Date().getTime()}.xlsx`)
}

getList()
</script>
